﻿using UnityEngine;
using System.Collections.Generic;

public class ShadowPanel : MonoBehaviour
{
    public Camera shadowCamera;

    private MeshFilter meshFilter;
    private Vector3[] vertices;
    private List<Vector2> uvs;
    private GameObject lit;
    private bool hasSetLit = false;

    void OnEnable()
    {

        meshFilter = GetComponent<MeshFilter>();
        vertices = meshFilter.mesh.vertices;
        uvs = new List<Vector2>(vertices.Length);
        for (int i = 0; i < meshFilter.mesh.vertexCount; ++i)
        {
            uvs.Add(Vector2.zero);
        }

        if (!hasSetLit)
        {
            if (lit == null)
            {
                lit = GameObject.FindGameObjectWithTag("SceneLight");
            }
            var ls = GameObject.FindObjectsOfType<Light>();
            foreach(var l in ls)
            {
                if(l.name != "UILight")
                {
                    lit = l.gameObject;
                    break;
                }
            }
            if (lit != null)
            {
                shadowCamera.transform.rotation = lit.transform.rotation;
            }

            hasSetLit = true;
        }

    }



    void OnWillRenderObject()
    {
        for (int i = 0; i < vertices.Length; ++i)
        {
            Vector3 p = transform.TransformPoint(vertices[i]);
            p = shadowCamera.WorldToViewportPoint(p);
            uvs[i] = new Vector2(p.x, p.y);
        }
        meshFilter.mesh.SetUVs(0, uvs);

    }


}
